package org.he.org.service.impl;

import org.he.basic.service.impl.BaseServiceImpl;
import org.he.org.domain.Department;
import org.he.org.mapper.IDepartmentMapper;
import org.he.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author He
 * @date 2023/11/28  19:44
 */
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private IDepartmentMapper departmentMapper;
    @Override
    @Transactional
    public void insert(Department department) {
        departmentMapper.insert(department);
        if (Objects.isNull(department.getParent().getId())){
            department.setPath("/" +department.getId());
        }else {
            Department department1 = departmentMapper.queryById(department.getParent().getId());
            department.setPath(department1.getPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }


    @Override
    @Transactional
    public void update(Department department) {
        if (Objects.isNull(department.getParent().getId())){
            department.setPath("/"+department.getId());
        }else {
            Department department1 = departmentMapper.queryById(department.getParent().getId());
            department.setPath(department1.getPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> getTree() {
        return departmentMapper.getTree();
    }
}
